/** 
Copyright (c) 2010, Sheikh Abdul Wahid Ahmed
Details @ http://extremecodeworld.codeplex.com/license
**/

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using EXtremecode.Utils;
using EXtremecode.DataAccessLayer;
using System.Data;
using EXtremecode.EntityDefinition;
using System.Xml;

namespace EXtremecode.EntityDefinitionGenerator
{
	/// <summary>
	/// Summary description for FrmGenerator.
	/// </summary>
	public class FrmGenerator : System.Windows.Forms.Form
    {
		private System.Windows.Forms.Button btnGenerateEntityDefinition;
		private System.Windows.Forms.ColumnHeader chEntityName;
		private System.Windows.Forms.ColumnHeader chConnectionName;
		private System.Windows.Forms.ColumnHeader chEntityType;
        private System.Windows.Forms.ListView lvTables;
		private System.Windows.Forms.CheckBox chkRefresh;
        private System.Windows.Forms.CheckBox chkRelatedEntities;
        private Button btnSelectAll;
        private Button btnDeselectAll;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public FrmGenerator()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmGenerator));
            this.chEntityName = new System.Windows.Forms.ColumnHeader();
            this.chConnectionName = new System.Windows.Forms.ColumnHeader();
            this.chEntityType = new System.Windows.Forms.ColumnHeader();
            this.lvTables = new System.Windows.Forms.ListView();
            this.chkRefresh = new System.Windows.Forms.CheckBox();
            this.chkRelatedEntities = new System.Windows.Forms.CheckBox();
            this.btnSelectAll = new System.Windows.Forms.Button();
            this.btnGenerateEntityDefinition = new System.Windows.Forms.Button();
            this.btnDeselectAll = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // chEntityName
            // 
            this.chEntityName.Text = "Entity";
            this.chEntityName.Width = 224;
            // 
            // chConnectionName
            // 
            this.chConnectionName.Text = "Connection";
            this.chConnectionName.Width = 105;
            // 
            // chEntityType
            // 
            this.chEntityType.Text = "Entity Type";
            this.chEntityType.Width = 71;
            // 
            // lvTables
            // 
            this.lvTables.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.lvTables.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.lvTables.CheckBoxes = true;
            this.lvTables.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
            this.chEntityName,
            this.chConnectionName,
            this.chEntityType});
            this.lvTables.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.lvTables.FullRowSelect = true;
            this.lvTables.GridLines = true;
            this.lvTables.Location = new System.Drawing.Point(3, 49);
            this.lvTables.Name = "lvTables";
            this.lvTables.Size = new System.Drawing.Size(553, 254);
            this.lvTables.Sorting = System.Windows.Forms.SortOrder.Ascending;
            this.lvTables.TabIndex = 3;
            this.lvTables.UseCompatibleStateImageBehavior = false;
            this.lvTables.View = System.Windows.Forms.View.Details;
            this.lvTables.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.lvTables_ItemCheck);
            this.lvTables.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.lvTables_ColumnClick);
            // 
            // chkRefresh
            // 
            this.chkRefresh.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.chkRefresh.BackColor = System.Drawing.Color.Transparent;
            this.chkRefresh.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.chkRefresh.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.chkRefresh.ForeColor = System.Drawing.Color.DarkOrange;
            this.chkRefresh.Location = new System.Drawing.Point(373, 4);
            this.chkRefresh.Name = "chkRefresh";
            this.chkRefresh.Size = new System.Drawing.Size(184, 17);
            this.chkRefresh.TabIndex = 6;
            this.chkRefresh.Text = "Refresh Selected Entities";
            this.chkRefresh.UseVisualStyleBackColor = false;
            // 
            // chkRelatedEntities
            // 
            this.chkRelatedEntities.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.chkRelatedEntities.BackColor = System.Drawing.Color.Transparent;
            this.chkRelatedEntities.Checked = true;
            this.chkRelatedEntities.CheckState = System.Windows.Forms.CheckState.Checked;
            this.chkRelatedEntities.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.chkRelatedEntities.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.chkRelatedEntities.ForeColor = System.Drawing.Color.DarkOrange;
            this.chkRelatedEntities.Location = new System.Drawing.Point(373, 19);
            this.chkRelatedEntities.Name = "chkRelatedEntities";
            this.chkRelatedEntities.Size = new System.Drawing.Size(175, 24);
            this.chkRelatedEntities.TabIndex = 6;
            this.chkRelatedEntities.Text = "Related Entities";
            this.chkRelatedEntities.UseVisualStyleBackColor = false;
            // 
            // btnSelectAll
            // 
            this.btnSelectAll.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.btnSelectAll.BackColor = System.Drawing.Color.Transparent;
            this.btnSelectAll.BackgroundImage = global::EntityDefinitionGenerator.Properties.Resources.ApplicationButton2;
            this.btnSelectAll.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
            this.btnSelectAll.FlatAppearance.BorderSize = 0;
            this.btnSelectAll.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Transparent;
            this.btnSelectAll.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
            this.btnSelectAll.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnSelectAll.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnSelectAll.ForeColor = System.Drawing.Color.White;
            this.btnSelectAll.Location = new System.Drawing.Point(176, 0);
            this.btnSelectAll.Name = "btnSelectAll";
            this.btnSelectAll.Size = new System.Drawing.Size(91, 30);
            this.btnSelectAll.TabIndex = 2;
            this.btnSelectAll.Text = "Check All";
            this.btnSelectAll.UseVisualStyleBackColor = false;
            this.btnSelectAll.Click += new System.EventHandler(this.btnSelectAll_Click);
            // 
            // btnGenerateEntityDefinition
            // 
            this.btnGenerateEntityDefinition.BackColor = System.Drawing.Color.Transparent;
            this.btnGenerateEntityDefinition.BackgroundImage = global::EntityDefinitionGenerator.Properties.Resources.ApplicationButton1;
            this.btnGenerateEntityDefinition.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
            this.btnGenerateEntityDefinition.FlatAppearance.BorderSize = 0;
            this.btnGenerateEntityDefinition.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Transparent;
            this.btnGenerateEntityDefinition.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
            this.btnGenerateEntityDefinition.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnGenerateEntityDefinition.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnGenerateEntityDefinition.ForeColor = System.Drawing.Color.White;
            this.btnGenerateEntityDefinition.Location = new System.Drawing.Point(3, -4);
            this.btnGenerateEntityDefinition.Name = "btnGenerateEntityDefinition";
            this.btnGenerateEntityDefinition.Size = new System.Drawing.Size(91, 38);
            this.btnGenerateEntityDefinition.TabIndex = 2;
            this.btnGenerateEntityDefinition.Text = "Generate";
            this.btnGenerateEntityDefinition.UseVisualStyleBackColor = false;
            this.btnGenerateEntityDefinition.Click += new System.EventHandler(this.btnGenerateEntityDefinition_Click);
            // 
            // btnDeselectAll
            // 
            this.btnDeselectAll.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.btnDeselectAll.BackColor = System.Drawing.Color.Transparent;
            this.btnDeselectAll.BackgroundImage = global::EntityDefinitionGenerator.Properties.Resources.ApplicationButton2;
            this.btnDeselectAll.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
            this.btnDeselectAll.FlatAppearance.BorderSize = 0;
            this.btnDeselectAll.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Transparent;
            this.btnDeselectAll.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;
            this.btnDeselectAll.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.btnDeselectAll.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.btnDeselectAll.ForeColor = System.Drawing.Color.White;
            this.btnDeselectAll.Location = new System.Drawing.Point(263, 0);
            this.btnDeselectAll.Name = "btnDeselectAll";
            this.btnDeselectAll.Size = new System.Drawing.Size(91, 30);
            this.btnDeselectAll.TabIndex = 2;
            this.btnDeselectAll.Text = "Uncheck All";
            this.btnDeselectAll.UseVisualStyleBackColor = false;
            this.btnDeselectAll.Click += new System.EventHandler(this.btnDeselectAll_Click);
            // 
            // FrmGenerator
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.BackColor = System.Drawing.Color.White;
            this.ClientSize = new System.Drawing.Size(560, 309);
            this.Controls.Add(this.chkRefresh);
            this.Controls.Add(this.btnDeselectAll);
            this.Controls.Add(this.btnSelectAll);
            this.Controls.Add(this.btnGenerateEntityDefinition);
            this.Controls.Add(this.lvTables);
            this.Controls.Add(this.chkRelatedEntities);
            this.Cursor = System.Windows.Forms.Cursors.Hand;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "FrmGenerator";
            this.Text = "Definition Generator";
            this.Load += new System.EventHandler(this.FrmGenerator_Load);
            this.ResumeLayout(false);

		}
		#endregion

		
		private DataSet dsTables;
		private XmlDocument xmlDoc;
		static void Main() 
		{
			Application.Run(new FrmGenerator());
		}
		private void btnGenerateEntityDefinition_Click(object sender, System.EventArgs e)
		{
            btnGenerateEntityDefinition.Visible = false;
            Application.DoEvents();

            try
            {
                XmlElement elementRoot;
                xmlDoc = UserInterface.GetEntityDefinitionDocument();
                Entity.Reset();
                DBEntity.CreateEntities(dsTables);
                elementRoot = Entity.GenerateXml(xmlDoc, chkRefresh.Checked);
                UserInterface.WriteEntityDefinition(elementRoot);
                Entity.ConvertToCustomXml(elementRoot);
                UserInterface.WriteEntityDefinition(elementRoot, "Custom");

                LoadEntitysAndDoRelatedTask();

                //create another xml by usiing entity definition xml, which will be used for customization.

                #region Customized Xml
                XmlAttribute atb;
                XmlDocument xmlDocCustomized = UserInterface.GetEntityCustomized();
                XmlElement customizedRootElement = GetRootElement(xmlDocCustomized);
                XmlNodeList entityNodes = XmlUtil.GetNodes(elementRoot,
                    "shk:entity[@name]", EntityDefinition.Configurations.Provider.XMLN, "shk");

                foreach (XmlElement entityElement in entityNodes)
                {
                    string entityName = entityElement.Attributes["name"].Value;

                    //check,wheather element of same entity in customized xml exsist or not.
                    //if doesnt exist then create it.
                    XmlNodeList customizedEntityNodes = XmlUtil.GetNodes(customizedRootElement,
                        string.Format("shk:entity[@name='{0}']", entityName),
                        EntityDefinition.Configurations.Provider.XMLN, "shk");
                    XmlElement customizedEntityElement;
                    XmlElement customizedFieldsElement;

                    if (customizedEntityNodes.Count == 0)
                    {
                        customizedEntityElement =
                            xmlDocCustomized.CreateElement(XMLSpecific.PREFIX, "entity", XMLSpecific.XMLN);
                        customizedRootElement.AppendChild(customizedEntityElement);

                        //'Name' Attribute
                        atb = xmlDocCustomized.CreateAttribute("name");
                        atb.InnerText = entityName;
                        customizedEntityElement.Attributes.Append(atb);

                        //'TypeCode' Attribute
                        atb = xmlDocCustomized.CreateAttribute("typeCode");
                        atb.InnerText = string.Empty; ;
                        customizedEntityElement.Attributes.Append(atb);

                        //Fields Element
                        customizedFieldsElement =
                            xmlDocCustomized.CreateElement(XMLSpecific.PREFIX, "fields", XMLSpecific.XMLN);
                        customizedEntityElement.AppendChild(customizedFieldsElement);


                    }
                    else
                    {
                        customizedEntityElement = customizedEntityNodes[0] as XmlElement;
                        customizedFieldsElement =
                            customizedEntityElement.GetElementsByTagName("fields", XMLSpecific.XMLN)[0] as XmlElement;
                    }

                    //same process for the fields

                    foreach (XmlElement entityFieldElement in
                        entityElement.GetElementsByTagName("field", XMLSpecific.XMLN))
                    {
                        string fieldName = entityFieldElement.Attributes["name"].Value;

                        //check,wheather element for the same field in customized xml exsist or not.
                        //if doesnt exist then create it.
                        XmlNodeList customizedFieldNodes = XmlUtil.GetNodes(customizedFieldsElement,
                            string.Format("shk:field[@name='{0}']", fieldName),
                            EntityDefinition.Configurations.Provider.XMLN, "shk");
                        XmlElement customizedFieldElement;

                        if (customizedFieldNodes.Count == 0)
                        {
                            customizedFieldElement =
                                xmlDocCustomized.CreateElement(XMLSpecific.PREFIX, "field", XMLSpecific.XMLN);
                            customizedFieldsElement.AppendChild(customizedFieldElement);

                            //'Name' Attribute
                            atb = xmlDocCustomized.CreateAttribute("name");
                            atb.InnerText = fieldName;
                            customizedFieldElement.Attributes.Append(atb);

                        }

                    }

                }
                XmlUtil.WriteXml(customizedRootElement, Configurations.Provider.EntityCustomizedPath);
                #endregion

                MessageBox.Show(string.Format("Entity Definitions have been generated successfully at the location \n {0}", EntityDefinition.Configurations.Provider.EntityDefinitionPath), "Generated Successfully", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
            finally
            {
                btnGenerateEntityDefinition.Visible = true;

            }
		}

		

		private void btnGenerateClasses_Click(object sender, System.EventArgs e)
		{
			try
			{
				UserInterface.CreateClasses();
				MessageBox.Show(string.Format("Classes have been generated successfully at the folder \n {0}",Configurations.Provider.ClassesDirectoryPath),"Generated Successfully",MessageBoxButtons.OK,MessageBoxIcon.Information);
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message ,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);

			}
			finally
			{
			}
		}

		private void btnCreateXtraCode_Click(object sender, System.EventArgs e)
		{
			try
			{
				UserInterface.CreateXtraCodeClass();
				MessageBox.Show(string.Format("Class has been generated successfully at the [Parent of] folder \n {0}",Configurations.Provider.ClassesDirectoryPath),"Generated Successfully",MessageBoxButtons.OK,MessageBoxIcon.Information);
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message ,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);

			}

		}
		private void PopulateListViewControl()
		{
			PopulateListViewControl(dsTables);
			lvTables.ListViewItemSorter=ListViewItemComparer.Instance;

		}
		private void PopulateListViewControl(DataSet ds)
		{
			foreach(DataTable dt in ds.Tables)
			{
				try
				{
					ListViewItem lvItem=new ListViewItem(new string[] {dt.TableName,dt.ExtendedProperties["AccessorName"].ToString(),dt.ExtendedProperties["Type"].ToString()});
					SetListViewItemToDataTable(dt,lvItem);
                    lvItem.ForeColor = Color.OliveDrab;
					lvTables.Items.Add(lvItem);
				}
				catch(Exception ex)
				{
					throw Logging.Logger.Write(ex,string.Format("Table Name = {0}",dt.TableName));
				}
			}
		}
				
		private ListViewItem GetListViewItemOfDataTable(DataTable dt)
		{
			ListViewItem lvItem=null;
			if(dt.ExtendedProperties.Contains("ListViewItem"))
			{
				lvItem= dt.ExtendedProperties["ListViewItem"] as ListViewItem;
			}
			return lvItem;
		}

		
		internal static void SetListViewItemToDataTable(DataTable dt,ListViewItem lvItem)
		{
			if(!dt.ExtendedProperties.Contains("ListViewItem"))
			{
				dt.ExtendedProperties.Add("ListViewItem",lvItem);
			}
			dt.ExtendedProperties["ListViewItem"]=lvItem; 
			lvItem.Tag=dt;

		}

		private void FrmGenerator_Load(object sender, System.EventArgs e)
		{
			try
			{
				BusinessObjectGenerator.ClassGenerate +=new GeneratorHandler(BusinessObjectGenerator_ClassGenerate);
				dsTables=new DataSet();
				
				DataAccessorCollection conns= DataAccessorCollection.Instance; 	
			
				foreach(object keys in conns.Keys)
				{
					DataAccessor da = conns[keys] as DataAccessor ;
					da.GenerateTablesImage(dsTables);
					da.GenerateViewsImage(dsTables);
				}
				PopulateListViewControl();
				LoadEntitysAndDoRelatedTask(); 
				
			

			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message ,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
				System.Windows.Forms.Application.Exit();

			}
			

		}
		private void LoadEntitysAndDoRelatedTask()
		{
			XmlElement elementRoot;
			xmlDoc=UserInterface.GetEntityDefinitionDocument();
			elementRoot=Entity.GetRootElement(xmlDoc);
			DataTable[] dts=Entity.GetListOfSelectedTables(elementRoot,dsTables);
			foreach(DataTable dt in dts)
			{
				ListViewItem lvItem=GetListViewItemOfDataTable(dt);
				lvItem.Checked=true;
				lvItem.BackColor=SystemColors.HighlightText;
                lvItem.ForeColor = SystemColors.Highlight;
				//lvItem.Font=new Font(lvItem.Font,FontStyle.Bold);
				lvItem.Text=dt.TableName; 
				
			}
		}
		private void lvTables_ItemCheck(object sender, System.Windows.Forms.ItemCheckEventArgs e)
		{
			bool bChecked=(e.CurrentValue!=CheckState.Checked);
			ListViewItem lvItem=lvTables.Items[e.Index];
			DataTable dt=lvItem.Tag as DataTable;
			Entity.SelectTableForEntity(dt,bChecked);
			if(chkRelatedEntities.Checked)
			{
				foreach(DataRelation rel in dt.ParentRelations)
				{
					ListViewItem lvi= GetListViewItemOfDataTable(rel.ParentTable);
					if(Entity.IsTableSelectedForEntity(rel.ParentTable)!=bChecked)
					{
						Entity.SelectTableForEntity(rel.ParentTable,bChecked);
						lvi.Checked=bChecked;
					}
				}
				foreach(DataRelation rel in dt.ChildRelations)
				{
					ListViewItem lvi= GetListViewItemOfDataTable(rel.ChildTable);
					if(Entity.IsTableSelectedForEntity(rel.ChildTable)!=bChecked)
					{
						lvi.Checked=bChecked;
     					Entity.SelectTableForEntity(rel.ChildTable,bChecked);
					}
				}
			}
		}
		private void CheckAllItems(bool bChecked)
		{
			foreach(ListViewItem lvItem in lvTables.Items)
			{
				lvItem.Checked=bChecked;
				Entity.SelectTableForEntity((lvItem.Tag as DataTable),bChecked);
			}
		}

		private void lvTables_ColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e)
		{
			
			ListViewItemComparer.Instance.Column=e.Column;
			lvTables.Sort();
		}

		private void btnDeselectAll_Click(object sender, System.EventArgs e)
		{
		CheckAllItems(false);
		}

		private void btnSelectAll_Click(object sender, System.EventArgs e)
		{
			CheckAllItems(true);
		}

		private void BusinessObjectGenerator_ClassGenerate(string message)
		{
			Application.DoEvents();
		}
		public static XmlElement GetRootElement(XmlDocument ownerDocument)
		{
			XmlElement element;
			XmlNodeList nodes=ownerDocument.GetElementsByTagName("entities",XMLSpecific.XMLN);
			if(nodes.Count>0)
				element=(XmlElement)nodes[0];
			else
				element= ownerDocument.CreateElement(XMLSpecific.PREFIX,"entities",XMLSpecific.XMLN);

			return element;
		}
	}
	// Implements the manual sorting of items by columns.
	class ListViewItemComparer : IComparer
	{
		private int col;
		private bool bAsc=true;
		private static ListViewItemComparer singleton;
		private ListViewItemComparer()
		{
			col = 0;
		}
		public int Column
		{
			get
			{
				return col;
			}
			set
			{
				if(col==value)bAsc=!bAsc; 
				col=value;
			}

		}
		public static ListViewItemComparer Instance
		{
			get
			{
				if(singleton==null)singleton=new ListViewItemComparer();
				return singleton;
			}
		}

			
		public int Compare(object x, object y)
		{
			if(!bAsc)
			{
				object temp=x;
				x=y;
				y=temp;
			}
			return String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text);
		}
		
	}
}
